<%= include ic/admin-header.html %>
<style>
.stock{background:#eee;border:1px solid #fff;padding:0 10px;}
.stock .label{width:50%;text-align:left;float:left;padding:10px;}
.stock .num{width:50%;float:left;padding:5px;}
</style>
<div class="am-cf admin-main">
  <%= include ic/admin-sidebar.html %>

  <!-- content start -->
  <div class="admin-content">
    <div class="am-cf am-padding">
      <div class="am-fl am-cf"><strong class="am-text-primary am-text-lg">商品管理</strong> / <small><% if(result){ %>编辑 - <%= result.get("title") %><% }else{ %>新建<% } %></small></div>
    </div>

	<div class="am-padding-left"></div>
    <hr style=" margin-top:0.5rem;" />
	<div class="am-g-fixed am-cf am-padding-left am-padding-bottom">
		<form class="am-form am-u-sm-12 am-form-horizontal am-cf" id="my-form">
			<% if(result){ %><input id="data-id" type="hidden" value="<%= result.id %>"><% } %>
			<div id="coverBox" class="am-u-sm-4 am-fl">
				<input id="data-cover" type="hidden" value="<% if(result && result.get('cover')){ %><%= result.get('cover') %><% } %>" >
        <input id="data-bcover" type="hidden" value="<% if(result && result.get('bcover')){ %><%= result.get('bcover') %><% } %>" >
				<div class="am-u-sm-12 am-nbfc">
					<img class="am-u-sm-12" id="imgCover" src="<% if(result && result.get('cover')){ %>/p?id=<%= result.get('cover') %><% }else{ %>/i/default.png<% } %>" />
          <img class="am-u-sm-12" id="imgBCover" src="<% if(result && result.get('bcover')){ %>/p?id=<%= result.get('bcover') %><% }else{ %>/i/default.png<% } %>" />
				</div>
				<div class="am-u-sm-12 am-cf"></div>
				<div class="am-form-group am-form-file am-u-sm-10 am-u-sm-centered am-padding-top">
					<button type="button" class="am-btn am-btn-danger am-btn-sm am-u-sm-centered" id="btn-uploadCover">
						<i class="am-icon-cloud-upload"></i> 选择要上传的图片</button>
					<input id="doc-form-file" type="file" accept="image/*" >
				</div>
			</div>
			<div class="am-u-sm-8 am-fr">
				<div class="am-form-group">
					<label for="data-title" class="am-u-sm-2 am-form-label">标题</label>
					<div class="am-u-sm-10">
						<input type="text" id="data-title" value="<% if(result){ %><%= result.get("title") %><% } %>" placeholder="2-170字符" data-foolish-msg="2-20字符的页面名" minlength="2" maxlength="170" required>
					</div>
				</div>

				<div class="am-form-group am-form-inline">
          <label for="data-brand" class="am-u-sm-2 am-form-label">品牌</label>
					<div class="am-u-sm-4">
            <select id="data-brand" data-am-selected="{searchBox: 1}" required>
              <% for(var i=0;i<brands.length;i++){ %>
							<option value="<%= brands[i].id %>" <% if(result && result.get("Brand").id==brands[i].id){ %>selected<% } %>><%= brands[i].get("name") %></option>
              <% } %>
						</select>
					</div>
          <label for="data-sex" class="am-u-sm-2 am-form-label">性别</label>
					<div class="am-u-sm-3">
            <select id="data-sex" multiple data-am-selected="{}" required>
              <option value="婴儿" <% if(result && result.get("sex").indexOf("婴儿")>-1){ %>selected<% } %>>婴儿</option>
							<option value="男孩" <% if(result && result.get("sex").indexOf("男孩")>-1){ %>selected<% } %>>男孩</option>
              <option value="女孩" <% if(result && result.get("sex").indexOf("女孩")>-1){ %>selected<% } %>>女孩</option>
						</select>
					</div>
					<div class="am-u-sm-1"></div>
				</div>
        <div class="am-form-group am-form-inline">
          <label for="data-type" class="am-u-sm-2 am-form-label">类型</label>
					<div class="am-u-sm-4">
            <select id="data-type" multiple data-am-selected="{searchBox: 1}" required>
              <% for(var i=0;i<data.type.length;i++){ %>
							<option value="<%= data.type[i] %>" <% if(result && result.get("type").indexOf(data.type[i])>-1){ %>selected<% } %>><%= data.type[i] %></option>
              <% } %>
						</select>
					</div>
          <label for="data-size" class="am-u-sm-2 am-form-label">尺码</label>
					<div class="am-u-sm-3">
            <select id="data-size" multiple data-am-selected="{searchBox: 1}" required onchange="reStock()">
              <% for(var i=0;i<data.size.length;i++){ %>
							<option value="<%= data.size[i] %>" <% if(result && result.get("size").indexOf(data.size[i])>-1){ %>selected<% } %>><%= data.size[i] %></option>
              <% } %>
						</select>
					</div>
          <div class="am-u-sm-1"></div>
				</div>
        <div class="am-form-group am-form-inline">
          <label for="data-type" class="am-u-sm-2 am-form-label">新品</label>
          <div class="am-u-sm-4">
            <select id="data-isnew" data-am-selected="{}" required>
              <option value="1" <% if(!result || result.get("isNew")==true){ %>selected<% } %>>是</option>
              <option value="0" <% if(result && result.get("isNew")==false){ %>selected<% } %>>否</option>
            </select>
          </div>
          <label for="data-price" class="am-u-sm-2 am-form-label">价格</label>
					<div class="am-u-sm-3">
            <input type="number" id="data-price" value="<% if(result && result.get("price")){ %><%= result.get("price") %><% }else{ %>0<% } %>">
					</div>
          <div class="am-u-sm-2"></div>
				</div>
        <div class="am-form-group am-form-inline">
          <label for="data-state" class="am-u-sm-2 am-form-label">状态</label>
					<div class="am-u-sm-3">
            <input type="text" id="data-state" value="<% if(result && result.get("enabled")){ %>已上架<% }else{ %>仓库<% } %>" disabled>
					</div>
          <label for="data-createdAt" class="am-u-sm-2 am-form-label">创建</label>
					<div class="am-u-sm-5">
            <input type="text" id="data-createdAt" value="<% if(result){ %><%= moment(result.createdAt).format('YYYY年MM月DD日 HH:mm:ss') %><% }else{ %><%= moment().format('YYYY年MM月DD日 HH:mm:ss') %><% } %>" disabled>
					</div>
				</div>
        <hr class="am-u-sm-12 am-fl am-cf" />
        <div class="am-form-group am-form-inline">
          <label class="am-u-sm-2 am-form-label">库存</label>
          <div class="am-u-sm-10"></div>
        </div>
        <div id="stockList">
          <% if(result && result.get("size")){ %>
          <% for(var i=0;i<result.get("size").length;i++){ %>
          <div class="am-form-group am-form-inline am-u-sm-6 stock">
            <div class="label"><%= result.get("size")[i] %></div>
            <div class="num">
              <input type="number" value="<% if(result.get("stock")[i]){ %><%= result.get("stock")[i] %><% }else{ %>0<% } %>" />
            </div>
          </div>
          <% } %>
          <% } %>
        </div>
        <div id="stockModel" style="display:none;">
          <div class="am-form-group am-form-inline am-u-sm-6 stock" data-id="-1">
          <div class="label">库存</div>
          <div class="num"><input type="number" value="0"></div>
          </div>
        </div>
			</div>
		</form>
		<hr class="am-u-sm-12 am-fl am-cf" />
    <ul data-am-widget="gallery" id="imglist" class="am-gallery am-avg-sm-4" data-am-gallery="{pureview: 1}">
      <% for(var i=0;i<images.length;i++){ %>
      <li>
        <div class="am-gallery-item">
          <img data-id="<%= images[i] %>" src="/p?id=<%= images[i] %>&w=300&h=300"
         data-rel="/p?id=<%= images[i] %>" class="am-img-responsive" />
          <div class="ctrBar"><a href="javascript:void(0)" onclick="delImg(this)">删除</a><a href="javascript:void(0)" onclick="upImg(this)">前移</a><a href="javascript:void(0)" onclick="setCover(this)">封面</a>
          <a href="javascript:void(0)" onclick="setBCover(this)">封底</a></div>
        </div>
      </li>
      <% } %>
    </ul>
    <hr class="am-u-sm-12 am-fl am-cf" />
		<div class="am-u-sm-12 am-fl">
			<link rel="stylesheet" type="text/css" href="/css/simditor.css">
			<link rel="stylesheet" type="text/css" href="/css/simditor-html.css">
			<textarea id="data-content" class="am-pre-scrollable" style="height:40rem;max-height:40rem;"><% if(result && result.get("content")){ %><%= result.get("content") %><% } %></textarea>
		</div>
		<hr class="am-u-sm-12 am-fl am-cf" />
		<div class="am-g am-u-sm-11 am-fl am-cf">
			<div class="am-u-sm-offset-1 am-u-sm-3">
				<div class="am-btn am-btn-default" onclick="history.go(-1)">返回列表</div>
			</div>
      <div class="am-u-sm-offset-1 am-u-sm-3">
				<div id="btn-saveEdit0" class="am-btn am-btn-primary btn-saveEdit" onclick="saveEdit(0)">存入仓库</div>
			</div>
			<div class="am-u-sm-offset-1 am-u-sm-3 am-u-end">
				<div id="btn-saveEdit1" class="am-btn am-btn-primary btn-saveEdit" onclick="saveEdit(1)">保存上架</div>
			</div>
		</div>
		<div class="am-u-sm-12 am-fl am-cf" ></div>
	</div>
  </div>
  <!-- content end -->

</div>

<a class="am-icon-btn am-icon-th-list am-show-sm-only admin-menu" data-am-offcanvas="{target: '#admin-offcanvas'}"></a>

<%= include ic/admin-footer.html %>
<style>
#imglist .am-gallery-item{border:5px solid #fff;}
#imglist li{position:relative;}
#imglist li
#imglist li  .am-icon-spinner{width:auto;height:auto;position:absolute;top:50%;left:50%;margin:-9px 0 0 -9px;}
#imglist .am-gallery-item{position:relative;}
#imglist .ctrBar{width:100%;position:absolute;bottom:0;left:0;text-align:right;background:rgba(0,0,0,0.7);}
#imglist .ctrBar a{padding:0 12px;}
</style>
<script type="text/javascript" src="/js/simditor/module.min.js"></script>
<script type="text/javascript" src="/js/simditor/hotkeys.min.js"></script>
<script type="text/javascript" src="/js/simditor/uploader.min.js"></script>
<script type="text/javascript" src="/js/simditor/simditor.min.js"></script>
<script type="text/javascript" src="/js/simditor/beautify-html.js"></script>
<script type="text/javascript" src="/js/simditor/simditor-html.js"></script>

<script type="text/javascript">
var refer	= "list";
var editor, toolbar,enabled=0;
var $loading = $("#my-modal-loading");
$(function() {
    toolbar = ['title', 'bold', 'italic', 'underline', 'color', '|', 'ol', 'ul', 'blockquote', 'table', '|', 'link', 'image', 'hr', '|', 'indent', 'outdent', 'alignment'];
    editor = new Simditor({
      textarea: $('#data-content'),
      placeholder: '这里输入文字...',
      toolbar: toolbar,
      pasteImage: true,
      defaultImage: '/i/default.png',
      upload: {
		url: '/admin/uploadImg',
		fileKey: 'uploadImg',
		connectionCount: 3,
		leaveConfirm: '正在上传图片..'
	  }
    });
});
$(function(){
	$("#collapse-nav").addClass("am-in");
	$("#doc-form-file").on("change",function(e){
		uploadImage2(this.files[0]);
	});
})
var validator 	= $('#my-form').validator({submit: function(e) {
	if(this.isFormValid()){
		//$.AMUI.progress.start();
    $loading.modal('open');
    var images  = $("#imglist li .am-img-responsive").map(function(){
      return $(this).attr("data-id");
    }).get();
    var size  = $("#data-size").val();
    var stock = [];
    var num   = 0;
    for(var i=0;i<size.length;i++){
      if($("#stockList .label:contains('"+size[i]+"')").size()>0){
        var ln  = $("#stockList .label:contains('"+size[i]+"')").parents(".stock").find("input").val();
        ln  = parseInt(ln);
        if(isNaN(ln))ln=0;
        stock.push(ln);
        num+=ln;
      }
    }
		$.post("./save", {
			"ajax"			: true,
			"id"			  : $('#data-id').val(),
			"content"		: editor.getValue(),
			"title"			: $('#data-title').val(),
			"num"		    : num,
      "stock"     : stock,
      "size"		  : $('#data-size').val(),
      "brand"		  : $('#data-brand').val(),
      "sex"		    : $('#data-sex').val(),
      "type"		  : $('#data-type').val(),
			"cover"			: $('#data-cover').val(),
      "bcover"		: $('#data-bcover').val(),
      "images"		: images,
      "price"			: $('#data-price').val(),
			"enabled"		: enabled
		},function(data){
      $loading.modal('close');
			//$.AMUI.progress.done();
      //console.dir(data);
			$(".btn-saveEdit").removeClass("am-disabled");
			if(typeof(data)=="object" && typeof(data.error)=="undefined"){
				mAlert({
					title:"提示",
					text:"保存成功！",
					onConfirm:function(e) {
						gotoUrl(refer);
					}
				});
			}else{
				//console.dir(data);
				mAlert({
					title:"错误",
					text:data.error,
					onConfirm:function(e) {}
				});
			}
		}, "json");
	}else{
		$("#btn-saveEdit").removeClass("am-disabled");
	}
	return false;
}});

function saveEdit(state){
  if(state==1)enabled=state;
	$(".btn-saveEdit").addClass("am-disabled");
	validator.submit();
}

function uploadImage2(file) {
	//var progress = $.AMUI.progress;
	//progress.configure({parent:'#imgCover'});
	$("#btn-uploadCover").addClass("am-disabled");
	if(!/image\/\w+/.test(file.type)){
    alert("文件必须为图片！");
		$("#btn-uploadCover").removeClass("am-disabled");
        return false;
  }
	var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function(e){
      if($("#imgCover").attr("src")=="/i/default.png"){
        $("#imgCover").attr("src",this.result);
      }
      var html = '<li>'+
          '<div class="am-gallery-item">'+
          '<img src="'+this.result+'" class="am-img-responsive last" />'+
          '<div class="ctrBar">'+
          '<a href="javascript:void(0)" onclick="delImg(this)">删除</a>'+
          '<a href="javascript:void(0)" onclick="upImg(this)">前移</a>'+
          '<a href="javascript:void(0)" onclick="setCover(this)">封面</a>'+
          '<a href="javascript:void(0)" onclick="setBCover(this)">封底</a>'+
          '</div>'+
          '</div>'+
          '<div class="am-icon-spinner am-icon-spin"></div>'+
          '</li>';
      $("#imglist").append(html);
    }
	//console.dir(file);
	//progress.start();
	var fd = new FormData();
	fd.append("uploadImg", file);
	var xhr = new XMLHttpRequest();
	xhr.upload.addEventListener("progress", function(evt){
		if (evt.lengthComputable) {
      var percentComplete = Math.round(evt.loaded/ evt.total);
      //progress.set(percentComplete);
    }
	}, false);
	xhr.addEventListener("load", function(evt){
		//progress.done(true);
		//console.dir(evt.target);
		$("#btn-uploadCover").removeClass("am-disabled");
		var img=eval('('+evt.target.responseText+')');
		console.log(evt.target.responseText);
		if(img.success){
      if($("#data-cover").val()==""){
        $("#data-cover").val(img.id);
      }
      $("#imglist .last").attr("data-id", img.id);
      $("#imglist .last").attr("data-rel", "/p?id="+img.id);
      $("#imglist .last").removeClass("last");
      $("#imglist .am-icon-spinner").remove();
			mAlert({title:"提示",text:"上传成功！"});
		}else{
      $("#imglist .last").remove();
			mAlert({title:"错误",text:img.msg});
		}
	}, false);
	xhr.addEventListener("error", function(evt){
		//progress.remove();
    $("#imglist .last").remove();
		$("#btn-uploadCover").removeClass("am-disabled");
		mAlert({title:"错误",text:"上传失败！"});
	}, false);
	xhr.addEventListener("abort", function(evt){
		//progress.remove();
    $("#imglist .last").remove();
		$("#btn-uploadCover").removeClass("am-disabled");
	}, false);
	xhr.open("POST", "/admin/uploadImg");
	xhr.send(fd);
}

function setCover(obj){
  var img=$(obj).parents(".am-gallery-item").children(".am-img-responsive");
  //console.log($(obj).parents(".am-gallery-item").html());
  //console.log($(img).attr("src"));
  $("#imgCover").attr("src",$(img).attr("src"));
  $('#data-cover').val($(img).attr("data-id"));
}

function setBCover(obj){
  var img=$(obj).parents(".am-gallery-item").children(".am-img-responsive");
  //console.log($(obj).parents(".am-gallery-item").html());
  //console.log($(img).attr("src"));
  $("#imgBCover").attr("src",$(img).attr("src"));
  $('#data-bcover').val($(img).attr("data-id"));
}

function delImg(obj){
  //console.log($(obj).parent().parent(".banner").html());
  $(obj).parents(".am-gallery-item").parent("li").remove();
}

function upImg(obj){
  var o=$(obj).parents(".am-gallery-item").parent("li");
  $(o).insertBefore($(o).prev());
}

function reStock(){
  var size=$("#data-size").val();
  for(var i=0;i<size.length;i++){
    if($("#stockList .label:contains('"+size[i]+"')").size()==0){
      $("#stockList").append($("#stockModel").html());
      $("#stockList .stock:last .label").text(size[i]);
    }
  }
  $("#stockList .stock").map(function(){
    var text=$(this).find(".label").text();
    if(size.indexOf(text)==-1){
      $(this).remove();
    }
  });
}
</script>
